package com.songlanyun.modules.express.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.google.gson.Gson;
import com.songlanyun.common.enums.GoodsConstant;
import com.songlanyun.common.enums.HouniaoConstant;
import com.songlanyun.common.exception.RRException;
import com.songlanyun.common.utils.HouniaoApiUtil;
import com.songlanyun.common.utils.R;
import com.songlanyun.modules.category.entity.SystemProductCategoryEntity;
import com.songlanyun.modules.category.service.SystemProductCategoryService;
import com.songlanyun.modules.express.model.JiSuKDUtil;
import com.songlanyun.modules.express.model.KDInfo;
import com.songlanyun.modules.goods.entity.Goods;
import com.songlanyun.modules.goods.entity.GoodsAuthShop;
import com.songlanyun.modules.goods.entity.GoodsSku;
import com.songlanyun.modules.goods.model.values.GoodsSkuTableItem;
import com.songlanyun.modules.goods.model.vo.GoodsSlimVo;
import com.songlanyun.modules.goods.service.GoodsAuthShopService;
import com.songlanyun.modules.goods.service.GoodsContentService;
import com.songlanyun.modules.goods.service.GoodsService;
import com.songlanyun.modules.goods.service.GoodsSkuService;
import com.songlanyun.modules.singlegoods.entity.ProductSingleGoodsEntity;
import com.songlanyun.modules.singlegoods.service.ProductSingleGoodsService;
import com.songlanyun.modules.skus.entity.ProductSkusEntity;
import com.songlanyun.modules.skus.service.ProductSkusService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.math.BigDecimal;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * 快递
 */
@RestController
@RequestMapping("api/express")
public class expressController {

    @Autowired
    private JiSuKDUtil jiSuKDUtil;

    @Autowired
    private HouniaoApiUtil houniaoApiUtil;

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private GoodsAuthShopService goodsAuthShopService;

    @Autowired
    private GoodsSkuService goodsSkuService;

    @Autowired
    private SystemProductCategoryService systemProductCategoryService;

    @Autowired
    private GoodsContentService goodsContentService;

    @Autowired
    private ProductSingleGoodsService productSingleGoodsService;

    @Autowired
    private ProductSkusService productSkusService;
    /**
     * 快递查询接口
     */

    @GetMapping("/selectKD/{expNo}/{mobile}")
    public R orderWholesaleconsign(@PathVariable("expNo") String expNo, @PathVariable("mobile") String mobile) {

        try {
            KDInfo kdInfo = jiSuKDUtil.getOrderTracesByJsonByMobile(expNo, mobile);
            if (ObjectUtil.isNull(kdInfo)) {
                return R.error("查询失败");
            }
            return R.ok("查询成功").put("data", kdInfo);
        } catch (Exception e) {
            return R.error("查询失败");
        }
    }

    @PostMapping("/test/demo")
    public R demo() {
        JSONObject req = new JSONObject();
        JSONObject js = houniaoApiUtil.client(req, HouniaoConstant.AREAS_LIST.getUrl());
        return R.ok().put("data", js);
    }

    /**
     * 商品保存
     * @return
     */
    @GetMapping("/test")
    public R test() {
        JSONObject req = new JSONObject();
        req.put("page_size",1);
        req.put("page_size",10);
        req.put("offset",0);
        JSONObject js = houniaoApiUtil.client(req, HouniaoConstant.GOODS_GET_LIST.getUrl());
        //获取数据
        JSONObject data = js.getJSONObject("data");
        //获取商品集合
        JSONArray data1 = data.getJSONArray("data");
        int size1 = data1.size();
        //遍历集合
        for (int i = 0;i < size1;i++){
            JSONObject jsonObject = data1.getJSONObject(i);
            Goods goods = new Goods();
            //shopId 30为候鸟
            goods.setShopId(35L);
            goods.setRealSaleNum(Integer.valueOf(jsonObject.get("sale_num").toString()));
            goods.setCover(jsonObject.getJSONObject("goods_img").get("img").toString());
            //分类id TODO: 存商品前，分好商品类  根据商品的spu去商品详情查
            //获取category_id_path 做判断
            String category_id_path = jsonObject.get("category_id_path").toString();
            //获取category_id_path的前两位
            category_id_path = category_id_path.substring(0,category_id_path.lastIndexOf("_"));
            //分类
            switch (category_id_path){
                case "1_2":
                    goods.setCategoryId(86L);
                    break;
                case "1_3":
                    goods.setCategoryId(96L);
                    break;
                case "1_20":
                    goods.setCategoryId(97L);
                    break;
                case "1_21":
                    goods.setCategoryId(98L);
                    break;
                case "1_22":
                    goods.setCategoryId(99L);
                    break;
                case "1_23":
                    goods.setCategoryId(100L);
                    break;
                case "1_24":
                    goods.setCategoryId(101L);
                    break;
                case "1_25":
                    goods.setCategoryId(102L);
                    break;
                case "1_26":
                    goods.setCategoryId(103L);
                    break;
                //婴儿工具
                case "1_ 1389":
                    //玩具
                case "1_27":
                    //图书
                case "1_1442":
                    goods.setCategoryId(104L);
                    break;
                case "1_28":
                    goods.setCategoryId(105L);
                    break;
                case "1_29":
                    goods.setCategoryId(106L);
                    break;
                case "7_118":
                case "7_1523":
                case "7_1529":
                case "7_1528":
                    goods.setCategoryId(115L);
                    break;
                case "7_135":
                case "7_133":
                case "10_432":
                    goods.setCategoryId(95L);
                    break;
                case "7_1530":
                case "7_1526":
                case "7_1527":
                case "10_383":
                case "10_405":
                case "10_424":
                    goods.setCategoryId(116L);
                    break;
                case "10_417":
                    goods.setCategoryId(91L);
                    break;
                case "9_283":
                    goods.setCategoryId(89L);
                    break;
                case "9_295":
                case "9_322":
                    goods.setCategoryId(112L);
                    break;
                case "9_305":
                    goods.setCategoryId(113L);
                    break;
                case "9_314":
                case "9_333":
                case "9_341":
                    goods.setCategoryId(114L);
                    break;
                case "9_339":
                case "9_374":
                case "9_376":
                case "9_378":
                case "9_380":
                    goods.setCategoryId(77L);
                    break;
                case "9_354":
                    goods.setCategoryId(107L);
                    break;
                case "9_356":
                    goods.setCategoryId(87L);
                    break;
                case "9_367":
                    goods.setCategoryId(113L);
                    break;
                case "9_382":
                    goods.setCategoryId(108L);
                    break;
                case "8_265":
                case "8_181":
                case "8_220":
                case "8_218":
                case "8_1561":
                case "8_1318":
                case "8_282":
                case "8_208":
                    goods.setCategoryId(90L);
                    break;
                case "519_520":
                    goods.setCategoryId(120L);
                    break;
                case "519_529":
                case "519_548":
                case "519_560":
                case "519_567":
                case "519_576":
                case "519_585":
                case "519_595":
                case "519_608":
                case "519_615":
                case "519_625":
                case "519_631":
                    goods.setCategoryId(91L);
                    break;
                case "519_537":
                    goods.setCategoryId(119L);
                    break;
                case "11_1409":
                    goods.setCategoryId(92L);
                    break;
                case "11_434":
                case "11_447":
                case "11_460":
                case "11_481":
                case "11_495":
                case "11_508":
                case "16_1420":
                case "16_1431":
                case "16_17":
                case "16_1321":
                case "16_1335":
                case "16_1336":
                case "16_1340":
                case "16_1343":
                case "16_1345":
                case "830_831":
                case "830_870":
                case "830_900":
                case "830_923":
                case "830_953":
                    goods.setCategoryId(82L);
                    break;
                case "13_633":
                    goods.setCategoryId(93L);
                    break;
                case "13_650":
                case "13_659":
                case "13_665":
                case "13_673":
                case "13_680":
                case "13_687":
                case "13_700":
                case "13_705":
                case "13_709":
                case "13_717":
                case "13_718":
                case "13_719":
                case "13_720":
                case "13_721":
                case "13_722":
                case "13_723":
                case "13_724":
                    goods.setCategoryId(83L);
                    break;
                case "14_772":
                case "14_816":
                case "14_820":
                case "14_829":
                case "14_751":
                    goods.setCategoryId(88L);
                    break;
                case "14_788":
                    goods.setCategoryId(109L);
                    break;
                case "14_802":
                    goods.setCategoryId(110L);
                    break;
                case "14_725":
                    goods.setCategoryId(111L);
                    break;
                case "19_146":
                case "19_151":
                case "19_164":
                case "19_171":
                case "19_178":
                case "19_179":
                case "19_156":
                case "19_1394":
                case "1055_1436":
                case "1055_1056":
                case "1055_1348":
                case "1055_1104":
                case "1055_1128":
                case "1055_1154":
                case "1055_1157":
                case "1055_1197":
                case "1055_1225":
                case "1055_1227":
                case "1229_1230":
                case "1243_1288":
                case "1243_1291":
                case "1243_1298":
                case "1243_1304":
                case "1243_1244":
                case "1243_1259":
                case "1243_1275":
                case "1243_1293":
                case "1315_1390":
                case "1315_1401":
                case "1315_1316":
                    goods.setCategoryId(81L);
                    break;
                case "955_1414":
                case "955_1450":
                case "955_956":
                case "955_960":
                case "955_962":
                    goods.setCategoryId(80L);
                    break;
                case "965_966":
                case "965_975":
                case "965_985":
                case "965_992":
                case "965_1001":
                    goods.setCategoryId(91L);
                    break;
                case "1004_1026":
                case "1004_1035":
                case "1004_1050":
                case "1004_1053":
                case "1004_1346":
                case "1004_1005":
                case "1004_1017":
                case "1229_1241":
                    goods.setCategoryId(78L);
                    break;
            }
            goods.setMinSalePrice(new BigDecimal(jsonObject.get("min_price").toString()));
            goods.setMaxSalePrice(new BigDecimal(jsonObject.get("min_price").toString()));
            goods.setMinMarketPrice(new BigDecimal(jsonObject.get("min_price").toString()));
            goods.setMaxMarketPrice(new BigDecimal(jsonObject.get("min_price").toString()));
            goods.setMinExchangePoint(new BigDecimal(0.00));
            goods.setTitle(jsonObject.get("goods_name").toString());
            goods.setVideoUrl("");
            goods.setShortTitle("");
            goods.setSpuCode(jsonObject.get("goods_spu").toString());
            //商品规格 添加商品时设置为null  添加商品规格时 更新字段
            goods.setGoodsSkuList(new  ArrayList<>());
            goods.setInitSaleNum(0);
            goods.setLimitBuyNum(0);
            //实际出售量
            goods.setRealSaleNum(Integer.valueOf(jsonObject.get("sale_num").toString()));
            //是否是积分兑换
            goods.setPointGoods(false);
            //浏览量
            goods.setPv(0L);
            goods.setVerifyStatus(GoodsConstant.VerifyStatus.YES);
            //顺序暂时为0 不知道干什么用的
            goods.setSort(Integer.valueOf(0));
            //是否是平台商品  暂时设置为不是
            goods.setPlatformStore(false);
            //运费模版 暂时写死
            goods.setFreightTemplateId(6);
            //最后审核时间  暂时设置为导入时间
            goods.setLastVerifyTime(new Date());
            //软删除  0正常 -1删除
            goods.setDeleted(0);
            goods.setCreateTime(new Date());
            goods.setUpdateTime(new Date());
            //是否开启会员折扣  暂时为false 不知道具体用途
            goods.setOpenUserDiscount(false);
            //暂时设置为热销
            goods.setHot(true);
            //是否是新品  暂时设置为不是
            goods.setNewGoods(false);
            //是否推荐 暂时设置为是
            goods.setRecommend(true);
            goods.setAverage(new BigDecimal(5.0));
            //是否可以代理销售暂时设置为false
            goods.setAbleProxySale(false);
            goods.setGiftType(GoodsConstant.GiftType.NO);
            //积分商品积分按商品价格来
            goods.setGivePoint(goods.getMinSalePrice());
            //赠送消费值 暂时写死 不知道计算原理
            goods.setConsumptionValue(goods.getMinSalePrice());
            goods.setFree(false);
            //是否是激活商品  暂时设置为是
            goods.setAreaFeature(GoodsConstant.AreaFeature.GENERAL);
            //三方的spuid暂时写死
            goods.setHouniaoSpuId(goods.getSpuCode());
            //是否是三方产品 暂时设置为是
            goods.setThird(true);
            //sorce  暂时给99
            goods.setSource(99);
            //规格
            goods.setSkuTable(new ArrayList());
            //图片 TODO:setImagesValue方法注释了，需要修改
//        goods.setImagesValue("https://images.houniao.hk/upload/goods/desc/1479869873820048793.jpg");
            //商品保存
            goodsService.create(goods);

            // 详情图片
            JSONObject xiangqing = new JSONObject();
            xiangqing.put("goods_spu", goods.getSpuCode());
            JSONObject xiangqingjs = houniaoApiUtil.client(xiangqing, HouniaoConstant.GOODS_GET_INFO.getUrl());
            // 遍历返回的"goods_desc_image"
            JSONObject data2 = xiangqingjs.getJSONObject("data");
            JSONArray goods_desc_image = data2.getJSONArray("goods_desc_image");
            StringBuilder goods_desc_image_url = new StringBuilder();
            String qian = "<img src=\"";
            // 遍历图片
            goods_desc_image.forEach(item -> {
                goods_desc_image_url.append(qian);
                goods_desc_image_url.append(item.toString());
                goods_desc_image_url.append("\">");
            });
            // StringBuilder -> String
            String goods_desc_image_urls = goods_desc_image_url.toString();
            String zuizhong = "<p>" + goods_desc_image_urls + "</p>";
            goodsContentService.setGoodsContent(goods.getId(), zuizhong);


            ProductSingleGoodsEntity ps = new ProductSingleGoodsEntity();
            ps.setGoodsGroupId(69L);
            ps.setGoodsGroupName("999");
            ps.setCode(goods.getSpuCode());
            ps.setTitle(goods.getTitle());
            ps.setCoverImage(goods.getCover());
            ps.setUnit(data2.get("unit_name").toString());
            ps.setCostPrice(goods.getMinSalePrice());
            ps.setOrderIndex(0);
            ps.setAbleStock(999999);
            ps.setDeleted(0);
            ps.setShopId(35L);
            ps.setSku(data2.get("unit_name").toString());
            ps.setAdded(true);
            productSingleGoodsService.add(ps.getShopId(),ps);

            // 商家所发商品的与店铺的授权关系表，平台店铺发的商品如A,平台会有一条店铺与商品的关系，商家店铺SS也要代销平台商品，则需要建立一条商品A也商品店铺SS的关系，店铺SS可以随时上下架这个平台商品
            GoodsAuthShop shop = new GoodsAuthShop();
            //商品id
            shop.setGoodsId(goods.getId());
            //是否上架
            shop.setAdded(true);
            //上架时间
            shop.setCreateTime(new Date());
            //上架状态时间
            shop.setAddedStatusTime(new Date());
            //更新时间
            shop.setUpdateTime(new Date());
            //商家授权id
            shop.setAuthorizeShopId(35L);
            //发表商家店铺
            shop.setPublishShopId(35L);

            goodsAuthShopService.add(goods.getShopId(),goods);
            //获取商品规格
            JSONObject req1 = new JSONObject();
            req1.put("goods_spu",goods.getSpuCode());
            JSONObject json = houniaoApiUtil.client(req1, HouniaoConstant.GOODS_GET_GOODS_SPEC_PRICE_BATCH.getUrl());
            JSONArray data3 = json.getJSONArray("data");
            JSONObject jsonObject1 = data3.getJSONObject(0);
            JSONArray sku_list = jsonObject1.getJSONArray("sku_list");

            // 准备一个goods表的拼接字符串
            StringBuilder sb = new StringBuilder();

            int size = sku_list.size();
            //规格集合
            List<GoodsSku> skuList = new ArrayList<>();
            for (int j = 0;j < size; j++){

                JSONObject jsonObject2 = JSON.parseObject(JSONObject.toJSONString(sku_list.get(j)));
                String sku_name = jsonObject2.getString("sku_name");
                // skus表新增
                ProductSkusEntity skusEntity = new ProductSkusEntity();
                skusEntity.setName(sku_name);
                skusEntity.setShopId(35L);
                skusEntity.setParentSkuId(53L);
                skusEntity.setOrderIndex(1);
                productSkusService.save(skusEntity);
                Long skusEntity_id = skusEntity.getId();

                // sku_relation表新增
                //商品的规格的关系表（一个商品可能会有多个规格，各个规格中要关联单品）
                GoodsSku goodsSku = new GoodsSku();
                goodsSku.setGoodsId(goods.getId());
                //单品id  不知道怎么用  暂时设置为sku_id  TODO:SingleGoodsId 设为 goodsId
                goodsSku.setSingleGoodsId(ps.getId());
                //暂时设置为规格价格
                goodsSku.setSalePrice(new BigDecimal(sku_list.getJSONObject(j).get("sku_price").toString()));
                //暂时设置为规格价格
                goodsSku.setMarketPrice(new BigDecimal(sku_list.getJSONObject(j).get("sku_price").toString()));

                goodsSku.setWeight(new BigDecimal(sku_list.getJSONObject(j).get("sku_weight").toString()));
                //体积暂时设为0
                goodsSku.setVolume(new BigDecimal(0));
                //规格组合配置的字符串设置 TODO:删除了setSkuSetValue中的方法需要修改
                String str ="[{\"value\": {\"name\": \"" + sku_name + "\",\"id\": \"" + skusEntity_id + "\"}}]";
                String str1 ="{\"name\":\"" + sku_name + "\",\"id\":\"" + skusEntity_id + "\"}";
                goodsSku.setSkuSetValue(str);
                //商品规格编码
                goodsSku.setBarCode(sku_list.getJSONObject(j).get("spec_sku").toString());
                //兑换积分暂时设置为0
                goodsSku.setExchangePoint(new BigDecimal(0));
                goodsSku.setCover(sku_list.getJSONObject(j).get("spec_img").toString());
                goodsSku.setSkuSetName(sku_list.getJSONObject(j).getJSONArray("sku_attribute_name").get(0).toString());
                //单品码 暂时设置为spu编码
                goodsSku.setSingleGoodsCode(goods.getSpuCode());
                //单品标题
                goodsSku.setSingleGoodsTitle(goods.getTitle());
                //sku_hash暂时写死 TODO:skuHashCode 为了快递查找 以后再说先写死  20位随机字符串
                goodsSku.setSkuHashCode(skusEntity_id.toString());
                goodsSku.setShopId(goods.getShopId());
                goodsSku.setThirdSkuId(Long.valueOf(sku_list.getJSONObject(j).get("sku_id").toString()));
                goodsSku.setAgreementPrice(new BigDecimal(0.00));
                //三方成本价 写死
                goodsSku.setThirdCostPrice(goodsSku.getSalePrice());
                //指导价 写死
                goodsSku.setGuidePrice(goodsSku.getSalePrice());
                skuList.add(goodsSku);
                // 拼接goods表要的字符串
                sb.append(str1 + ",");
            }

            goodsSkuService.branchCreate(goods.getId(),skuList);
// 最后给goods表的sku_table_value字段拼接好 head块
            // StringBuilder -> String 并且去除最后的逗号

            if (sb.length() > 0){
                String string = sb.substring(0, sb.length() - 1);
                System.out.println(string);
                string = "[{\"values\":["+string+"],\"head\":{\"name\":\"产品\",\"id\":53}}]";
                System.out.println(string);
                String s = "[{\"values\":[{\"name\":\"柔雾紫200g（适合偏黄黄黑人群）\",\"id\":269},\"head\":{\"name\":\"数量\",\"id\":96}}]";

                goods.setSkuTableValue(string);
            }
            // 商品表img_value
            JSONObject goods_img = data2.getJSONObject("goods_img");
            String img = goods_img.get("img").toString();
            String imgValue = "[\"" + img + "\"]";
            goods.setImagesValue(imgValue);

            goods.setGoodsSkuList(skuList);
            goodsService.updateById(goods);
        }
        return R.ok().put("data","商品添加成功");
    }
    @GetMapping("/test/sku_list")
    public R sku_list() {
//        Goods goods = goodsService.getById(866L,true);
//        goods.setImagesValue("https://images.houniao.hk/upload/goods/desc/1479869873820048793.jpg");
        JSONObject req = new JSONObject();
//        req.put("goods_spu","BS00000005");
//        JSONObject js = houniaoApiUtil.client(req, "goods_category/get_list");
//        JSONArray data2 = js.getJSONArray("data");
//        JSONObject jsonObject1 = data2.getJSONObject(0);
//        JSONArray sku_list = jsonObject1.getJSONArray("sku_list");
//        String sku_attribute_name = sku_list.getJSONObject(1).getJSONArray("sku_attribute_name").get(1).toString();
//        System.err.println(sku_attribute_name);
//        JSONObject req = new JSONObject();
//        req.put("page_size",1);
        req.put("offset",0);
        JSONObject js = houniaoApiUtil.client(req, HouniaoConstant.GOODS_GET_LIST.getUrl());
        return R.ok().put("data", js);
    }
    @GetMapping("goods_category/get_list")
    public R goods_category_get_list() {
        JSONObject req = new JSONObject();
        JSONObject js = houniaoApiUtil.client(req, "goods_category/get_list");
        JSONArray data = js.getJSONArray("data");
//        for (int i = 0;i < data.size();i++){
            SystemProductCategoryEntity systemProductCategory = new SystemProductCategoryEntity();

            JSONObject jsonObject = data.getJSONObject(0);
            systemProductCategory.setId(200L);
            //设置parentId
            systemProductCategory.setParentId(Long.valueOf(jsonObject.get("pid").toString()));
            //设置分类名称Name
            systemProductCategory.setName(jsonObject.get("name").toString());
            //设置分类顺序
            systemProductCategory.setOrderIndex(1);
            //设置图标
            systemProductCategory.setCoverImage(jsonObject.get("image").toString());
            //是否推荐到首页 暂时设为是
            systemProductCategory.setRecommend(true);
            //分类说明
            systemProductCategory.setRemark(null);
            systemProductCategoryService.save(systemProductCategory);
//        }


        return R.ok().put("data", "ok");
    }
    @GetMapping("/getCategoryGetList")
    public R categoryGetList() {
        JSONObject req = new JSONObject();
        JSONObject js = houniaoApiUtil.client(req, "goods_category/get_list");
        return R.ok().put("data", js);
    }



}
